<!--
* @Author: zhuxiaoyi
* @Date: 2024-01-09 10:50:36
* @LastEditor: zhuxiaoyi
* @LastEditTime: 2024-08-27 10:05:44
* @Description: 动态数据组件 - 支持实时数据更新、图表展示、筛选和分页
-->
<template>
  <div class="dynamic-component" :style="{ height: view.height + 'px' }">
    <!-- 头部控制区域 -->
    <div class="header-controls">
      <div class="title-section">
        <h2>{{ componentTitle }}</h2>
        <span class="data-count">共 {{ filteredData.length }} 条数据</span>
      </div>
      
      <div class="control-buttons">
        <el-button type="primary" @click="refreshData" :loading="loading">
          <el-icon><Refresh /></el-icon>
          刷新数据
        </el-button>
        <el-button @click="toggleAutoRefresh">
          {{ autoRefresh ? '停止自动刷新' : '开启自动刷新' }}
        </el-button>
        <el-button @click="exportData">
          <el-icon><Download /></el-icon>
          导出数据
        </el-button>
      </div>
    </div>

    <!-- 筛选区域 -->
    <div class="filter-section">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-input
            v-model="filters.search"
            placeholder="搜索..."
            clearable
            @input="handleSearch"
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
        </el-col>
        <el-col :span="6">
          <el-select v-model="filters.category" placeholder="选择分类" clearable @change="handleFilter">
            <el-option
              v-for="category in categories"
              :key="category"
              :label="category"
              :value="category"
            />
          </el-select>
        </el-col>
        <el-col :span="6">
          <el-date-picker
            v-model="filters.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            @change="handleFilter"
          />
        </el-col>
        <el-col :span="6">
          <el-select v-model="filters.status" placeholder="状态筛选" clearable @change="handleFilter">
            <el-option label="全部" value="" />
            <el-option label="活跃" value="active" />
            <el-option label="待处理" value="pending" />
            <el-option label="已完成" value="completed" />
          </el-select>
        </el-col>
      </el-row>
    </div>

    <!-- 统计卡片区域 -->
    <div class="stats-section">
      <el-row :gutter="20">
        <el-col :span="6" v-for="stat in statistics" :key="stat.key">
          <el-card class="stat-card">
            <div class="stat-content">
              <div class="stat-icon" :class="stat.iconClass">
                <el-icon :size="24" v-if="stat.icon">
                  <component :is="stat.icon" />
                </el-icon>
              </div>
              <div class="stat-details">
                <div class="stat-value">{{ stat.value }}</div>
                <div class="stat-label">{{ stat.label }}</div>
                <div class="stat-change" :class="stat.changeClass">
                  {{ stat.change }}
                </div>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 多图表展示区域 -->
    <div class="charts-grid">
      <!-- 第一行：主要趋势图表 -->
      <el-row :gutter="20" class="chart-row">
        <el-col :span="12">
          <el-card class="chart-card">
            <template #header>
              <div class="chart-header">
                <span>数据趋势分析</span>
                <el-select v-model="trendChartType" size="small" @change="updateTrendChart">
                  <el-option label="折线图" value="line" />
                  <el-option label="面积图" value="area" />
                  <el-option label="柱状图" value="bar" />
                </el-select>
              </div>
            </template>
            <div ref="trendChartContainer" class="chart-container"></div>
          </el-card>
        </el-col>
        <el-col :span="12">
          <el-card class="chart-card">
            <template #header>
              <span>分类占比分析</span>
            </template>
            <div ref="pieChartContainer" class="chart-container"></div>
          </el-card>
        </el-col>
      </el-row>

      <!-- 第二行：仪表盘和雷达图 -->
      <el-row :gutter="20" class="chart-row">
        <el-col :span="8">
          <el-card class="chart-card">
            <template #header>
              <span>完成率仪表盘</span>
            </template>
            <div ref="gaugeChartContainer" class="chart-container"></div>
          </el-card>
        </el-col>
        <el-col :span="8">
          <el-card class="chart-card">
            <template #header>
              <span>多维度雷达图</span>
            </template>
            <div ref="radarChartContainer" class="chart-container"></div>
          </el-card>
        </el-col>
        <el-col :span="8">
          <el-card class="chart-card">
            <template #header>
              <span>散点分布图</span>
            </template>
            <div ref="scatterChartContainer" class="chart-container"></div>
          </el-card>
        </el-col>
      </el-row>

      <!-- 第三行：热力图和漏斗图 -->
      <el-row :gutter="20" class="chart-row">
        <el-col :span="12">
          <el-card class="chart-card">
            <template #header>
              <div class="chart-header">
                <span>时间热力图</span>
                <el-switch v-model="heatmapCalendar" @change="updateHeatmapChart" 
                  active-text="日历模式" inactive-text="矩阵模式" />
              </div>
            </template>
            <div ref="heatmapChartContainer" class="chart-container"></div>
          </el-card>
        </el-col>
        <el-col :span="12">
          <el-card class="chart-card">
            <template #header>
              <span>数据流程漏斗图</span>
            </template>
            <div ref="funnelChartContainer" class="chart-container"></div>
          </el-card>
        </el-col>
      </el-row>

      <!-- 第四行：关系图和桑基图 -->
      <el-row :gutter="20" class="chart-row">
        <el-col :span="12">
          <el-card class="chart-card">
            <template #header>
              <span>关系网络图</span>
            </template>
            <div ref="networkChartContainer" class="chart-container"></div>
          </el-card>
        </el-col>
        <el-col :span="12">
          <el-card class="chart-card">
            <template #header>
              <span>数据流向桑基图</span>
            </template>
            <div ref="sankeyChartContainer" class="chart-container"></div>
          </el-card>
        </el-col>
      </el-row>

      <!-- 第五行：3D图表和K线图 -->
      <el-row :gutter="20" class="chart-row">
        <el-col :span="8">
          <el-card class="chart-card">
            <template #header>
              <span>3D柱状图</span>
            </template>
            <div ref="bar3dChartContainer" class="chart-container"></div>
          </el-card>
        </el-col>
        <el-col :span="8">
          <el-card class="chart-card">
            <template #header>
              <span>K线图</span>
            </template>
            <div ref="candlestickChartContainer" class="chart-container"></div>
          </el-card>
        </el-col>
        <el-col :span="8">
          <el-card class="chart-card">
            <template #header>
              <span>树状图</span>
            </template>
            <div ref="treemapChartContainer" class="chart-container"></div>
          </el-card>
        </el-col>
      </el-row>

      <!-- 第六行：仪表盘集群和极坐标图 -->
      <el-row :gutter="20" class="chart-row">
        <el-col :span="12">
          <el-card class="chart-card">
            <template #header>
              <span>多指标仪表盘</span>
            </template>
            <div ref="multiGaugeChartContainer" class="chart-container"></div>
          </el-card>
        </el-col>
        <el-col :span="12">
          <el-card class="chart-card">
            <template #header>
              <span>极坐标柱状图</span>
            </template>
            <div ref="polarChartContainer" class="chart-container"></div>
          </el-card>
        </el-col>
      </el-row>
    </div>
  </div>
</template>

<script setup lang="ts">
import { defineComponent, reactive, ref, toRefs, onMounted, watch, computed, onUnmounted, nextTick } from "vue";
import * as echarts from 'echarts';
import { ElMessage, ElMessageBox } from "element-plus";
import { 
  Refresh, 
  Download, 
  Search, 
  TrendCharts, 
  User, 
  DataBoard, 
  Monitor 
} from '@element-plus/icons-vue';

// 定义数据类型
interface DataItem {
  id: number;
  name: string;
  category: string;
  value: number;
  status: 'active' | 'pending' | 'completed';
  createTime: Date;
}

interface Statistics {
  key: string;
  label: string;
  value: string | number;
  change: string;
  changeClass: string;
  icon: any;
  iconClass: string;
}

// 响应式数据
const loading = ref(false);
const autoRefresh = ref(false);
const componentTitle = ref('动态数据管理');
const trendChartType = ref('line');
const heatmapCalendar = ref(true);
let refreshTimer: number | null = null;

// 图表实例引用
const trendChartContainer = ref<HTMLElement>();
const pieChartContainer = ref<HTMLElement>();
const gaugeChartContainer = ref<HTMLElement>();
const radarChartContainer = ref<HTMLElement>();
const scatterChartContainer = ref<HTMLElement>();
const heatmapChartContainer = ref<HTMLElement>();
const funnelChartContainer = ref<HTMLElement>();
const networkChartContainer = ref<HTMLElement>();
const sankeyChartContainer = ref<HTMLElement>();
const bar3dChartContainer = ref<HTMLElement>();
const candlestickChartContainer = ref<HTMLElement>();
const treemapChartContainer = ref<HTMLElement>();
const multiGaugeChartContainer = ref<HTMLElement>();
const polarChartContainer = ref<HTMLElement>();

// 图表实例
let trendChartInstance: echarts.ECharts | null = null;
let pieChartInstance: echarts.ECharts | null = null;
let gaugeChartInstance: echarts.ECharts | null = null;
let radarChartInstance: echarts.ECharts | null = null;
let scatterChartInstance: echarts.ECharts | null = null;
let heatmapChartInstance: echarts.ECharts | null = null;
let funnelChartInstance: echarts.ECharts | null = null;
let networkChartInstance: echarts.ECharts | null = null;
let sankeyChartInstance: echarts.ECharts | null = null;
let bar3dChartInstance: echarts.ECharts | null = null;
let candlestickChartInstance: echarts.ECharts | null = null;
let treemapChartInstance: echarts.ECharts | null = null;
let multiGaugeChartInstance: echarts.ECharts | null = null;
let polarChartInstance: echarts.ECharts | null = null;

// 视图配置
const view = reactive({
  height: window.innerHeight - 100,
});

// 筛选器
const filters = reactive({
  search: '',
  category: '',
  dateRange: null as [Date, Date] | null,
  status: ''
});

// 分页配置
const pagination = reactive({
  currentPage: 1,
  pageSize: 20
});

// 原始数据
const rawData = ref<DataItem[]>([]);
const selectedRows = ref<DataItem[]>([]);

// 模拟数据生成
const generateMockData = (): DataItem[] => {
  const categories = ['系统', '网络', '安全', '性能', '用户'];
  const statuses: ('active' | 'pending' | 'completed')[] = ['active', 'pending', 'completed'];
  
  return Array.from({ length: 100 }, (_, index) => ({
    id: index + 1,
    name: `数据项目 ${index + 1}`,
    category: categories[Math.floor(Math.random() * categories.length)],
    value: Math.floor(Math.random() * 1000) + 1,
    status: statuses[Math.floor(Math.random() * statuses.length)],
    createTime: new Date(Date.now() - Math.random() * 30 * 24 * 60 * 60 * 1000)
  }));
};

// 计算属性
const categories = computed(() => {
  return [...new Set(rawData.value.map(item => item.category))];
});

const filteredData = computed(() => {
  let result = rawData.value;

  // 搜索筛选
  if (filters.search) {
    result = result.filter(item => 
      item.name.toLowerCase().includes(filters.search.toLowerCase()) ||
      item.category.toLowerCase().includes(filters.search.toLowerCase())
    );
  }

  // 分类筛选
  if (filters.category) {
    result = result.filter(item => item.category === filters.category);
  }

  // 状态筛选
  if (filters.status) {
    result = result.filter(item => item.status === filters.status);
  }

  // 日期范围筛选
  if (filters.dateRange && filters.dateRange.length === 2) {
    const [startDate, endDate] = filters.dateRange;
    result = result.filter(item => {
      const itemDate = new Date(item.createTime);
      return itemDate >= startDate && itemDate <= endDate;
    });
  }

  return result;
});

const paginatedData = computed(() => {
  const start = (pagination.currentPage - 1) * pagination.pageSize;
  const end = start + pagination.pageSize;
  return filteredData.value.slice(start, end);
});
// 图表相关方法
const initAllCharts = () => {
  initTrendChart();
  initPieChart();
  initGaugeChart();
  initRadarChart();
  initScatterChart();
  initHeatmapChart();
  initFunnelChart();
  initNetworkChart();
  initSankeyChart();
  initBar3dChart();
  initCandlestickChart();
  initTreemapChart();
  initMultiGaugeChart();
  initPolarChart();
};

const initTrendChart = () => {
  if (trendChartContainer.value) {
    trendChartInstance = echarts.init(trendChartContainer.value);
    updateTrendChart();
  }
};

const updateTrendChart = () => {
  if (!trendChartInstance) return;

  const dates = Array.from({ length: 30 }, (_, i) => {
    const date = new Date();
    date.setDate(date.getDate() - 29 + i);
    return date.toISOString().split('T')[0];
  });

  const data = dates.map(() => Math.floor(Math.random() * 1000) + 200);

  let option: any = {
    title: { text: '30天数据趋势', left: 'center', textStyle: { fontSize: 14 } },
    tooltip: { trigger: 'axis' },
    grid: { left: '10%', right: '10%', bottom: '15%' },
    xAxis: { 
      type: 'category', 
      data: dates.map(date => date.split('-').slice(1, 3).join('/')),
      axisLabel: { rotate: 45 }
    },
    yAxis: { type: 'value' },
    series: [{
      data: data,
      type: trendChartType.value,
      smooth: true,
      areaStyle: trendChartType.value === 'area' ? {} : undefined,
      itemStyle: { color: '#5470c6' }
    }]
  };

  trendChartInstance.setOption(option);
};

const initPieChart = () => {
  if (pieChartContainer.value) {
    pieChartInstance = echarts.init(pieChartContainer.value);
    updatePieChart();
  }
};

const updatePieChart = () => {
  if (!pieChartInstance) return;

  const categoryData = categories.value.map(cat => {
    const items = filteredData.value.filter(item => item.category === cat);
    return { name: cat, value: items.length };
  });

  const option = {
    title: { text: '分类分布', left: 'center', textStyle: { fontSize: 14 } },
    tooltip: { trigger: 'item', formatter: '{a} <br/>{b}: {c} ({d%})' },
    legend: { orient: 'vertical', left: 'left', top: 'middle' },
    series: [{
      name: '分类',
      type: 'pie',
      radius: ['40%', '70%'],
      center: ['60%', '50%'],
      data: categoryData,
      emphasis: { itemStyle: { shadowBlur: 10, shadowOffsetX: 0, shadowColor: 'rgba(0, 0, 0, 0.5)' } }
    }]
  };

  pieChartInstance.setOption(option);
};

const initGaugeChart = () => {
  if (gaugeChartContainer.value) {
    gaugeChartInstance = echarts.init(gaugeChartContainer.value);
    updateGaugeChart();
  }
};

const updateGaugeChart = () => {
  if (!gaugeChartInstance) return;

  const completedCount = filteredData.value.filter(item => item.status === 'completed').length;
  const completionRate = filteredData.value.length > 0 ? (completedCount / filteredData.value.length * 100) : 0;

  const option = {
    series: [{
      type: 'gauge',
      center: ['50%', '60%'],
      startAngle: 200,
      endAngle: -40,
      min: 0,
      max: 100,
      splitNumber: 10,
      itemStyle: { color: '#58D9F9', shadowColor: 'rgba(0,138,255,0.45)', shadowBlur: 10, shadowOffsetX: 2, shadowOffsetY: 2 },
      progress: { show: true, roundCap: true, width: 18 },
      pointer: { length: '60%', width: 8, offsetCenter: [0, '5%'] },
      axisLine: { roundCap: true, lineStyle: { width: 18 } },
      axisTick: { splitNumber: 2, lineStyle: { width: 2, color: '#999' } },
      axisLabel: { distance: 30, color: '#999', fontSize: 12 },
      title: { show: false },
      detail: {
        backgroundColor: '#fff',
        borderColor: '#999',
        borderWidth: 2,
        width: '60%',
        lineHeight: 40,
        height: 40,
        borderRadius: 8,
        offsetCenter: [0, '35%'],
        valueAnimation: true,
        formatter: function (value: number) { return '{value|' + value.toFixed(0) + '}{unit|%}'; },
        rich: {
          value: { fontSize: 20, fontWeight: 'bolder', color: '#777' },
          unit: { fontSize: 16, color: '#999', padding: [0, 0, -20, 10] }
        }
      },
      data: [{ value: completionRate, name: '完成率' }]
    }]
  };

  gaugeChartInstance.setOption(option);
};

const initRadarChart = () => {
  if (radarChartContainer.value) {
    radarChartInstance = echarts.init(radarChartContainer.value);
    updateRadarChart();
  }
};

const updateRadarChart = () => {
  if (!radarChartInstance) return;

  const option = {
    title: { text: '多维度分析', left: 'center', textStyle: { fontSize: 14 } },
    legend: { data: ['当前数据', '目标数据'], bottom: 10 },
    radar: {
      indicator: [
        { name: '数据量', max: 100 },
        { name: '活跃度', max: 100 },
        { name: '完成率', max: 100 },
        { name: '响应时间', max: 100 },
        { name: '用户满意度', max: 100 },
        { name: '系统稳定性', max: 100 }
      ],
      center: ['50%', '55%'],
      radius: 80
    },
    series: [{
      name: '多维度分析',
      type: 'radar',
      data: [
        {
          value: [65, 78, 82, 90, 75, 88],
          name: '当前数据',
          itemStyle: { color: '#5470c6' }
        },
        {
          value: [80, 85, 90, 95, 85, 95],
          name: '目标数据',
          itemStyle: { color: '#91cc75' }
        }
      ]
    }]
  };

  radarChartInstance.setOption(option);
};

const initScatterChart = () => {
  if (scatterChartContainer.value) {
    scatterChartInstance = echarts.init(scatterChartContainer.value);
    updateScatterChart();
  }
};

const updateScatterChart = () => {
  if (!scatterChartInstance) return;

  const scatterData = filteredData.value.map(item => [
    item.value,
    Math.random() * 100,
    item.category
  ]);

  const option = {
    title: { text: '数值分布散点图', left: 'center', textStyle: { fontSize: 14 } },
    tooltip: { trigger: 'item', formatter: (params: any) => `${params.data[2]}<br/>X: ${params.data[0]}<br/>Y: ${params.data[1].toFixed(2)}` },
    grid: { left: '10%', right: '10%', bottom: '15%' },
    xAxis: { type: 'value', name: '数值' },
    yAxis: { type: 'value', name: '权重' },
    series: [{
      type: 'scatter',
      data: scatterData,
      symbolSize: (data: any) => Math.sqrt(data[0]) / 5 + 5,
      itemStyle: { opacity: 0.7 }
    }]
  };

  scatterChartInstance.setOption(option);
};

const initHeatmapChart = () => {
  if (heatmapChartContainer.value) {
    heatmapChartInstance = echarts.init(heatmapChartContainer.value);
    updateHeatmapChart();
  }
};

const updateHeatmapChart = () => {
  if (!heatmapChartInstance) return;

  if (heatmapCalendar.value) {
    // 日历热力图
    const data = Array.from({ length: 365 }, (_, i) => {
      const date = new Date();
      date.setDate(date.getDate() - 364 + i);
      return [date.toISOString().split('T')[0], Math.floor(Math.random() * 100)];
    });

    const option = {
      title: { text: '年度活跃度日历', left: 'center', textStyle: { fontSize: 14 } },
      tooltip: { position: 'top', formatter: (params: any) => `${params.data[0]}: ${params.data[1]}` },
      visualMap: {
        min: 0,
        max: 100,
        calculable: true,
        orient: 'horizontal',
        left: 'center',
        bottom: '10%',
        inRange: { color: ['#e0f3ff', '#1890ff'] }
      },
      calendar: {
        top: 60,
        left: 30,
        right: 30,
        cellSize: ['auto', 13],
        range: new Date().getFullYear(),
        itemStyle: { borderWidth: 0.8 },
        yearLabel: { show: false }
      },
      series: [{
        type: 'heatmap',
        coordinateSystem: 'calendar',
        data: data
      }]
    };

    heatmapChartInstance.setOption(option);
  } else {
    // 矩阵热力图
    const hours = ['12a', '1a', '2a', '3a', '4a', '5a', '6a', '7a', '8a', '9a', '10a', '11a', '12p', '1p', '2p', '3p', '4p', '5p', '6p', '7p', '8p', '9p', '10p', '11p'];
    const days = ['Saturday', 'Friday', 'Thursday', 'Wednesday', 'Tuesday', 'Monday', 'Sunday'];
    const data = [];

    for (let i = 0; i < 7; i++) {
      for (let j = 0; j < 24; j++) {
        data.push([j, i, Math.floor(Math.random() * 100)]);
      }
    }

    const option = {
      title: { text: '活跃时间热力图', left: 'center', textStyle: { fontSize: 14 } },
      tooltip: { position: 'top', formatter: (params: any) => `${hours[params.data[0]]} ${days[params.data[1]]}: ${params.data[2]}` },
      grid: { height: '50%', top: '10%' },
      xAxis: { type: 'category', data: hours, splitArea: { show: true } },
      yAxis: { type: 'category', data: days, splitArea: { show: true } },
      visualMap: {
        min: 0,
        max: 100,
        calculable: true,
        orient: 'horizontal',
        left: 'center',
        bottom: '5%'
      },
      series: [{
        name: '活跃度',
        type: 'heatmap',
        data: data,
        label: { show: true },
        emphasis: { itemStyle: { shadowBlur: 10, shadowColor: 'rgba(0, 0, 0, 0.5)' } }
      }]
    };

    heatmapChartInstance.setOption(option);
  }
};

const initFunnelChart = () => {
  if (funnelChartContainer.value) {
    funnelChartInstance = echarts.init(funnelChartContainer.value);
    updateFunnelChart();
  }
};

const updateFunnelChart = () => {
  if (!funnelChartInstance) return;

  const option = {
    title: { text: '数据处理流程', left: 'center', textStyle: { fontSize: 14 } },
    tooltip: { trigger: 'item', formatter: '{a} <br/>{b} : {c}%' },
    series: [{
      name: '流程',
      type: 'funnel',
      left: '10%',
      top: 60,
      bottom: 60,
      width: '80%',
      sort: 'descending',
      gap: 2,
      label: { show: true, position: 'inside' },
      labelLine: { length: 10, lineStyle: { width: 1, type: 'solid' } },
      itemStyle: { borderColor: '#fff', borderWidth: 1 },
      emphasis: { label: { fontSize: 20 } },
      data: [
        { value: 100, name: '数据采集' },
        { value: 80, name: '数据清洗' },
        { value: 60, name: '数据验证' },
        { value: 40, name: '数据分析' },
        { value: 20, name: '结果输出' }
      ]
    }]
  };

  funnelChartInstance.setOption(option);
};

const initNetworkChart = () => {
  if (networkChartContainer.value) {
    networkChartInstance = echarts.init(networkChartContainer.value);
    updateNetworkChart();
  }
};

const updateNetworkChart = () => {
  if (!networkChartInstance) return;

  const nodes = [
    { id: '1', name: '中心节点', symbolSize: 50, x: 0, y: 0 },
    { id: '2', name: '节点A', symbolSize: 30, x: 100, y: 100 },
    { id: '3', name: '节点B', symbolSize: 30, x: -100, y: 100 },
    { id: '4', name: '节点C', symbolSize: 30, x: 100, y: -100 },
    { id: '5', name: '节点D', symbolSize: 30, x: -100, y: -100 },
    { id: '6', name: '子节点1', symbolSize: 20, x: 150, y: 150 },
    { id: '7', name: '子节点2', symbolSize: 20, x: -150, y: 150 }
  ];

  const links = [
    { source: '1', target: '2' },
    { source: '1', target: '3' },
    { source: '1', target: '4' },
    { source: '1', target: '5' },
    { source: '2', target: '6' },
    { source: '3', target: '7' }
  ];

  const option = {
    title: { text: '关系网络图', left: 'center', textStyle: { fontSize: 14 } },
    tooltip: {},
    series: [{
      type: 'graph',
      layout: 'force',
      symbolSize: 50,
      roam: true,
      label: { show: true },
      edgeSymbol: ['circle', 'arrow'],
      edgeSymbolSize: [4, 10],
      data: nodes,
      links: links,
      categories: [{ name: '节点' }],
      force: { repulsion: 1000, edgeLength: 100 },
      lineStyle: { opacity: 0.9, width: 2, curveness: 0 }
    }]
  };

  networkChartInstance.setOption(option);
};

const initSankeyChart = () => {
  if (sankeyChartContainer.value) {
    sankeyChartInstance = echarts.init(sankeyChartContainer.value);
    updateSankeyChart();
  }
};

const updateSankeyChart = () => {
  if (!sankeyChartInstance) return;

  const option = {
    title: { text: '数据流向桑基图', left: 'center', textStyle: { fontSize: 14 } },
    tooltip: { trigger: 'item', triggerOn: 'mousemove' },
    series: [{
      type: 'sankey',
      data: [
        { name: '源数据A' },
        { name: '源数据B' },
        { name: '源数据C' },
        { name: '处理模块1' },
        { name: '处理模块2' },
        { name: '输出结果' }
      ],
      links: [
        { source: '源数据A', target: '处理模块1', value: 10 },
        { source: '源数据B', target: '处理模块1', value: 15 },
        { source: '源数据C', target: '处理模块2', value: 8 },
        { source: '处理模块1', target: '输出结果', value: 20 },
        { source: '处理模块2', target: '输出结果', value: 5 }
      ],
      emphasis: { focus: 'adjacency' },
      lineStyle: { color: 'gradient', curveness: 0.5 }
    }]
  };

  sankeyChartInstance.setOption(option);
};

const initBar3dChart = () => {
  if (bar3dChartContainer.value) {
    bar3dChartInstance = echarts.init(bar3dChartContainer.value);
    updateBar3dChart();
  }
};

const updateBar3dChart = () => {
  if (!bar3dChartInstance) return;

  const data = [];
  for (let i = 0; i < 5; i++) {
    for (let j = 0; j < 5; j++) {
      data.push([i, j, Math.floor(Math.random() * 100)]);
    }
  }

  const option = {
    title: { text: '3D柱状图', left: 'center', textStyle: { fontSize: 14 } },
    tooltip: {},
    visualMap: {
      max: 100,
      inRange: { color: ['#313695', '#4575b4', '#74add1', '#abd9e9', '#e0f3f8', '#ffffcc', '#fee090', '#fdae61', '#f46d43', '#d73027', '#a50026'] }
    },
    xAxis3D: { type: 'category', data: ['A', 'B', 'C', 'D', 'E'] },
    yAxis3D: { type: 'category', data: ['1', '2', '3', '4', '5'] },
    zAxis3D: { type: 'value' },
    grid3D: {
      boxWidth: 200,
      boxDepth: 80,
      viewControl: { distance: 200 },
      light: { main: { intensity: 1.2, shadow: true }, ambient: { intensity: 0.3 } }
    },
    series: [{
      type: 'bar3D',
      data: data.map(item => ({ value: [item[0], item[1], item[2]] })),
      shading: 'lambert',
      label: { textStyle: { fontSize: 16, borderWidth: 1 } },
      emphasis: { label: { textStyle: { fontSize: 20, color: '#900' } }, itemStyle: { color: '#900' } }
    }]
  };

  bar3dChartInstance.setOption(option);
};

const initCandlestickChart = () => {
  if (candlestickChartContainer.value) {
    candlestickChartInstance = echarts.init(candlestickChartContainer.value);
    updateCandlestickChart();
  }
};

const updateCandlestickChart = () => {
  if (!candlestickChartInstance) return;

  const data = [];
  const dates = [];
  let basePrice = 100;

  for (let i = 0; i < 30; i++) {
    const date = new Date();
    date.setDate(date.getDate() - 29 + i);
    dates.push(date.toISOString().split('T')[0]);

    const open = basePrice + (Math.random() - 0.5) * 10;
    const close = open + (Math.random() - 0.5) * 15;
    const high = Math.max(open, close) + Math.random() * 5;
    const low = Math.min(open, close) - Math.random() * 5;
    
    data.push([open, close, low, high]);
    basePrice = close;
  }

  const option = {
    title: { text: 'K线图示例', left: 'center', textStyle: { fontSize: 14 } },
    tooltip: { trigger: 'axis', axisPointer: { type: 'cross' } },
    grid: { left: '10%', right: '10%', bottom: '15%' },
    xAxis: { type: 'category', data: dates.map(date => date.split('-').slice(1, 3).join('/')) },
    yAxis: { scale: true },
    series: [{
      type: 'candlestick',
      data: data,
      itemStyle: {
        color: '#ec0000',
        color0: '#00aa00',
        borderColor: '#8A0000',
        borderColor0: '#008F00'
      }
    }]
  };

  candlestickChartInstance.setOption(option);
};

const initTreemapChart = () => {
  if (treemapChartContainer.value) {
    treemapChartInstance = echarts.init(treemapChartContainer.value);
    updateTreemapChart();
  }
};

const updateTreemapChart = () => {
  if (!treemapChartInstance) return;

  const option = {
    title: { text: '树状图', left: 'center', textStyle: { fontSize: 14 } },
    tooltip: { trigger: 'item', formatter: '{b}: {c}' },
    series: [{
      type: 'treemap',
      data: [
        {
          name: '系统模块',
          value: 40,
          children: [
            { name: '用户管理', value: 15 },
            { name: '权限控制', value: 10 },
            { name: '日志记录', value: 15 }
          ]
        },
        {
          name: '业务模块',
          value: 60,
          children: [
            { name: '数据处理', value: 25 },
            { name: '报表生成', value: 20 },
            { name: 'API接口', value: 15 }
          ]
        }
      ]
    }]
  };

  treemapChartInstance.setOption(option);
};

const initMultiGaugeChart = () => {
  if (multiGaugeChartContainer.value) {
    multiGaugeChartInstance = echarts.init(multiGaugeChartContainer.value);
    updateMultiGaugeChart();
  }
};

const updateMultiGaugeChart = () => {
  if (!multiGaugeChartInstance) return;

  const option = {
    title: { text: '多指标仪表盘', left: 'center', textStyle: { fontSize: 14 } },
    series: [
      {
        type: 'gauge',
        center: ['25%', '50%'],
        radius: '60%',
        min: 0,
        max: 100,
        splitNumber: 10,
        axisLine: { lineStyle: { width: 10 } },
        axisTick: { distance: -30, length: 8, lineStyle: { color: '#fff', width: 2 } },
        axisLabel: { distance: -20, fontSize: 10 },
        detail: { fontSize: 12, offsetCenter: [0, '70%'], formatter: '{value}%' },
        data: [{ value: 75, name: 'CPU使用率' }],
        title: { fontSize: 10, offsetCenter: [0, '80%'] }
      },
      {
        type: 'gauge',
        center: ['75%', '50%'],
        radius: '60%',
        min: 0,
        max: 100,
        splitNumber: 10,
        axisLine: { lineStyle: { width: 10, color: [[0.3, '#67e0e3'], [0.7, '#37a2da'], [1, '#fd666d']] } },
        axisTick: { distance: -30, length: 8, lineStyle: { color: '#fff', width: 2 } },
        axisLabel: { distance: -20, fontSize: 10 },
        detail: { fontSize: 12, offsetCenter: [0, '70%'], formatter: '{value}%' },
        data: [{ value: 45, name: '内存使用率' }],
        title: { fontSize: 10, offsetCenter: [0, '80%'] }
      }
    ]
  };

  multiGaugeChartInstance.setOption(option);
};

const initPolarChart = () => {
  if (polarChartContainer.value) {
    polarChartInstance = echarts.init(polarChartContainer.value);
    updatePolarChart();
  }
};

const updatePolarChart = () => {
  if (!polarChartInstance) return;

  const data = [];
  for (let i = 0; i <= 360; i++) {
    const t = (i / 180) * Math.PI;
    const r = Math.sin(2 * t) * Math.cos(2 * t);
    data.push([r, i]);
  }

  const option = {
    title: { text: '极坐标柱状图', left: 'center', textStyle: { fontSize: 14 } },
    polar: { center: ['50%', '54%'] },
    tooltip: { trigger: 'axis', axisPointer: { type: 'cross' } },
    angleAxis: { type: 'value', startAngle: 0 },
    radiusAxis: { min: 0 },
    series: [
      {
        coordinateSystem: 'polar',
        name: '数据1',
        type: 'bar',
        data: Array.from({ length: 12 }, (_, i) => [Math.random() * 5, i * 30]),
        colorBy: 'data'
      },
      {
        coordinateSystem: 'polar',
        name: '数据2',
        type: 'bar',
        data: Array.from({ length: 12 }, (_, i) => [Math.random() * 3, i * 30 + 15]),
        colorBy: 'data'
      }
    ],
    legend: { show: true, data: ['数据1', '数据2'], bottom: 5 }
  };

  polarChartInstance.setOption(option);
};

const resizeAllCharts = () => {
  const charts = [
    trendChartInstance, pieChartInstance, gaugeChartInstance, radarChartInstance,
    scatterChartInstance, heatmapChartInstance, funnelChartInstance, networkChartInstance,
    sankeyChartInstance, bar3dChartInstance, candlestickChartInstance, treemapChartInstance,
    multiGaugeChartInstance, polarChartInstance
  ];
  
  charts.forEach(chart => {
    if (chart) {
      chart.resize();
    }
  });
};

const disposeAllCharts = () => {
  const charts = [
    trendChartInstance, pieChartInstance, gaugeChartInstance, radarChartInstance,
    scatterChartInstance, heatmapChartInstance, funnelChartInstance, networkChartInstance,
    sankeyChartInstance, bar3dChartInstance, candlestickChartInstance, treemapChartInstance,
    multiGaugeChartInstance, polarChartInstance
  ];
  
  charts.forEach(chart => {
    if (chart) {
      chart.dispose();
    }
  });
};
const statistics = computed((): Statistics[] => {
  const total = rawData.value.length;
  const active = rawData.value.filter(item => item.status === 'active').length;
  const pending = rawData.value.filter(item => item.status === 'pending').length;
  const avgValue = rawData.value.length > 0 
    ? Math.round(rawData.value.reduce((sum, item) => sum + item.value, 0) / rawData.value.length)
    : 0;

  return [
    {
      key: 'total',
      label: '总数据量',
      value: total,
      change: '+12%',
      changeClass: 'positive',
      icon: DataBoard,
      iconClass: 'icon-blue'
    },
    {
      key: 'active',
      label: '活跃数据',
      value: active,
      change: '+5%',
      changeClass: 'positive',
      icon: Monitor,
      iconClass: 'icon-green'
    },
    {
      key: 'pending',
      label: '待处理',
      value: pending,
      change: '-3%',
      changeClass: 'negative',
      icon: User,
      iconClass: 'icon-orange'
    },
    {
      key: 'average',
      label: '平均值',
      value: avgValue,
      change: '+8%',
      changeClass: 'positive',
      icon: TrendCharts,
      iconClass: 'icon-purple'
    }
  ];
});

// 方法
const refreshData = async () => {
  loading.value = true;
  try {
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 1000));
    rawData.value = generateMockData();
    ElMessage.success('数据刷新成功');
  } catch (error) {
    ElMessage.error('数据刷新失败');
  } finally {
    loading.value = false;
  }
};

const toggleAutoRefresh = () => {
  autoRefresh.value = !autoRefresh.value;
  
  if (autoRefresh.value) {
    refreshTimer = window.setInterval(() => {
      refreshData();
    }, 30000); // 30秒自动刷新
    ElMessage.info('已开启自动刷新，每30秒更新一次');
  } else {
    if (refreshTimer) {
      clearInterval(refreshTimer);
      refreshTimer = null;
    }
    ElMessage.info('已关闭自动刷新');
  }
};

const exportData = () => {
  // 简单的CSV导出
  const headers = ['ID', '名称', '分类', '数值', '状态', '创建时间'];
  const csvData = filteredData.value.map(item => [
    item.id,
    item.name,
    item.category,
    item.value,
    getStatusLabel(item.status),
    formatDate(item.createTime)
  ]);
  
  const csvContent = [headers, ...csvData]
    .map(row => row.join(','))
    .join('\n');
  
  const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' });
  const link = document.createElement('a');
  link.href = URL.createObjectURL(blob);
  link.download = `数据导出_${new Date().toISOString().split('T')[0]}.csv`;
  link.click();
  
  ElMessage.success('数据导出成功');
};

const handleSearch = () => {
  pagination.currentPage = 1;
};

const handleFilter = () => {
  pagination.currentPage = 1;
};

const handleSelectionChange = (selection: DataItem[]) => {
  selectedRows.value = selection;
};

const handleSortChange = ({ column, prop, order }: any) => {
  // 实现排序逻辑
  console.log('Sort change:', { column, prop, order });
};

const handleView = (row: DataItem) => {
  ElMessage.info(`查看: ${row.name}`);
};

const handleEdit = (row: DataItem) => {
  ElMessage.info(`编辑: ${row.name}`);
};

const handleDelete = async (row: DataItem) => {
  try {
    await ElMessageBox.confirm(`确定要删除 "${row.name}" 吗？`, '确认删除', {
      type: 'warning'
    });
    
    const index = rawData.value.findIndex(item => item.id === row.id);
    if (index > -1) {
      rawData.value.splice(index, 1);
      ElMessage.success('删除成功');
    }
  } catch {
    ElMessage.info('已取消删除');
  }
};

// 工具函数
const getValueType = (value: number) => {
  if (value > 800) return 'success';
  if (value > 400) return 'warning';
  return 'danger';
};

const formatValue = (value: number) => {
  return value.toLocaleString();
};

const getStatusType = (status: string) => {
  const types: Record<string, string> = {
    active: 'success',
    pending: 'warning',
    completed: 'info'
  };
  return types[status] || 'info';
};

const getStatusLabel = (status: string) => {
  const labels: Record<string, string> = {
    active: '活跃',
    pending: '待处理',
    completed: '已完成'
  };
  return labels[status] || status;
};

const formatDate = (date: Date) => {
  return new Date(date).toLocaleString('zh-CN');
};

// 窗口大小调整
const debounce = (func: Function, wait: number) => {
  let timeout: number;
  return function executedFunction(...args: any[]) {
    const later = () => {
      clearTimeout(timeout);
      func.apply(this, args);
    };
    clearTimeout(timeout);
    timeout = window.setTimeout(later, wait);
  };
};

const handleResize = debounce(() => {
  view.height = window.innerHeight - 100;
  resizeAllCharts();
}, 100);

// 生命周期
onMounted(async () => {
  window.addEventListener('resize', handleResize);
  await refreshData();
  await nextTick();
  initAllCharts();
});

onUnmounted(() => {
  window.removeEventListener('resize', handleResize);
  if (refreshTimer) {
    clearInterval(refreshTimer);
  }
  disposeAllCharts();
});

// 监听筛选数据变化，更新所有图表
watch(filteredData, () => {
  nextTick(() => {
    updateTrendChart();
    updatePieChart();
    updateGaugeChart();
    updateRadarChart();
    updateScatterChart();
    updateHeatmapChart();
    updateFunnelChart();
    updateNetworkChart();
    updateSankeyChart();
    updateBar3dChart();
    updateCandlestickChart();
    updateTreemapChart();
    updateMultiGaugeChart();
    updatePolarChart();
  });
}, { deep: true });
</script>

<style lang="scss" scoped>
.dynamic-component {
  padding: 20px;
  // background-color: #f5f7fa;
  overflow-y: auto;

  .header-controls {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    padding: 20px;
    // background: white;
    border-radius: 8px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);

    .title-section {
      h2 {
        margin: 0;
        color: #303133;
        font-size: 24px;
      }

      .data-count {
        color: #909399;
        font-size: 14px;
      }
    }

    .control-buttons {
      display: flex;
      gap: 12px;
    }
  }

  .filter-section {
    margin-bottom: 20px;
    padding: 20px;
    // background: white;
    border-radius: 8px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  }

  .stats-section {
    margin-bottom: 20px;

    .stat-card {
      .stat-content {
        display: flex;
        align-items: center;
        gap: 16px;

        .stat-icon {
          width: 48px;
          height: 48px;
          border-radius: 8px;
          display: flex;
          align-items: center;
          justify-content: center;

          &.icon-blue { background: #e3f2fd; color: #1976d2; }
          &.icon-green { background: #e8f5e8; color: #4caf50; }
          &.icon-orange { background: #fff3e0; color: #ff9800; }
          &.icon-purple { background: #f3e5f5; color: #9c27b0; }
        }

        .stat-details {
          flex: 1;

          .stat-value {
            font-size: 24px;
            font-weight: bold;
            color: #303133;
          }

          .stat-label {
            color: #909399;
            font-size: 14px;
            margin: 4px 0;
          }

          .stat-change {
            font-size: 12px;
            font-weight: 500;

            &.positive { color: #67c23a; }
            &.negative { color: #f56c6c; }
          }
        }
      }
    }
  }

  .charts-grid {
    .chart-row {
      margin-bottom: 20px;
    }

    .chart-card {
      height: 400px;

      .chart-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
      }

      .chart-container {
        height: 320px;
        width: 100%;
      }
    }
  }
}
</style>

<style lang="scss">
// 全局样式
.el-card {
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.el-table {
  .el-tag {
    font-size: 12px;
  }
}
</style>